package com.authine.cloudpivot.ext.service.impl;

import cn.hutool.core.stream.CollectorUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.exceptions.ServiceException;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.domain.bizservice.BizDatabaseConnectionPool;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.service.bizservice.BizDatabaseConnectionPoolService;
import com.authine.cloudpivot.engine.service.datasource.DataSourceService;
import com.authine.cloudpivot.engine.service.datasource.MyColumnMapRowMapper;
import com.authine.cloudpivot.engine.service.impl.datasource.TemplateDynamicMultiDataSource;
import com.authine.cloudpivot.ext.service.ZcOrgService;
import com.authine.cloudpivot.ext.utils.SchemaUtils;
import com.sun.corba.se.impl.corba.NamedValueImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author hxd
 * @Date 2022/3/16 18:55
 * @Description
 **/
@Slf4j
@Service
public class ZcOrgServiceImpl implements ZcOrgService {
    @PersistenceContext
     EntityManager entityManager;
    @Autowired
    private BizDatabaseConnectionPoolService connectionPoolService;
    @Autowired
    private BizObjectFacade bizObjectFacade;



    public List<Map<String, Object>> getVirtualSetting(){
        String sql = "SELECT JSON_UNQUOTE(xnbm -> '$[0].id') as  xnbm,JSON_UNQUOTE(stbm -> '$[*].id')  as stbm  from  ".concat(bizObjectFacade.getTableName(SchemaUtils.virtualDept));
        List<Map<String,Object>> resultList = entityManager.createNativeQuery(sql).unwrap(NativeQueryImpl.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();


        return resultList;
    }

    @Override
    public JSONArray getAllOrg() {

        String sql = "select REPLACE(id,'-','') as id,name,leaf, REPLACE(managerId,'-','') as managerId,REPLACE(parentId,'-','') as parentId,deleted from view_organizationunit_eac ";

//        List<Map<String,Object>> resultList = entityManager.createNativeQuery(sql).unwrap(NativeQueryImpl.class)
//                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        List<Map<String, Object>> resultList = getDataSourceService().getJdbcTemplate().query(sql, new HashMap<>(), new MyColumnMapRowMapper());
        JSONArray objects = JSONArray.parseArray(JSON.toJSONString(resultList));

        return objects;
    }



    private DataSourceService getDataSourceService(){
        String dbConnPoolCode = "zcOrgDb";
        BizDatabaseConnectionPool connectionPool = this.connectionPoolService.getByCode(dbConnPoolCode);

        if (connectionPool == null) {
            throw new ServiceException(ErrCode.BIZ_DATA_BASE_POOL_CODE_INVALID, "数据库连接池编码无效");
        } else {
            String datasourceType = connectionPool.getDatasourceType();
            String databaseType = connectionPool.getDatabaseType();
            String type = datasourceType + "." + databaseType;
            DataSourceService dataSourceService = (DataSourceService) TemplateDynamicMultiDataSource.getDataSourceService(dbConnPoolCode, type, JSON.toJSONString(connectionPool));
            return dataSourceService;
       }

    }


    @Override
    public JSONArray getorgByPid(List<String> pids) {

        if (CollectionUtils.isEmpty(pids)){
            return new JSONArray();
        }

        StringBuilder sql = new StringBuilder("select REPLACE(id,'-','') as id,name,leaf, REPLACE(managerId,'-','') as managerId,REPLACE(parentId,'-','') as parentId,deleted from view_organizationunit_eac where ");

        String pidStr = pids.stream().collect(Collectors.joining("','"));

        sql.append(" REPLACE(parentId,'-','') in ('").append(pidStr).append("') or REPLACE(id,'-','') in('").append(pidStr).append("') ");

//        List<Map<String,Object>> resultList = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class)
//                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        List<Map<String,Object>> resultList = getDataSourceService().getJdbcTemplate().query(sql.toString(), new HashMap<>(), new MyColumnMapRowMapper());

        JSONArray objects = JSONArray.parseArray(JSON.toJSONString(resultList));

        return objects;
    }

    @Override
    public JSONArray getUserByDeptId(final String deptId) {


        String sql = "select REPLACE(id,'-','') as id,name,REPLACE(departmentId,'-','') as departmentId,mobile,username,deleted from view_user_eac where "
                .concat(" username != 'admin' and REPLACE(departmentId,'-','') ='").concat(deptId).concat("'");

//        List<Map<String,Object>> resultList = entityManager.createNativeQuery(sql).unwrap(NativeQueryImpl.class)
//                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        List<Map<String,Object>> resultList = getDataSourceService().getJdbcTemplate().query(sql, new HashMap<>(), new MyColumnMapRowMapper());

        JSONArray objects = JSONArray.parseArray(JSON.toJSONString(resultList));

        return objects;
    }

    @Override
    public Map<String, Object> getUserSimpleInfoByUsername(final String username) {
        String sql = "select a.zyfzdj, a.zwcj,zyjndj, a.zyjszw,b.route,a.gzsj,a.zw,a.zdsj from view_user_eac  a  LEFT JOIN view_organizationunit_eac b on a.departmentId = b.id where "
                .concat(" a.username ='").concat(username).concat("'");
        try {
            Map<String, Object> map = getDataSourceService().getJdbcTemplate().queryForObject(sql, new HashMap<>(), new MyColumnMapRowMapper());
            return map;
        } catch (Exception e) {
            log.info(e.getMessage(),e);
            return new HashMap<>();
        }
    }
}
